/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.alibaba.fastjson.JSONObject;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.scene.domain.DeviceHiddenDanger;
import com.koron.scene.domain.TeamHandover;
import com.koron.scene.domain.TeamHandoverRelation;
import com.koron.scene.service.api.TeamHandoverService;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "teamHandover", description = "班组交接接口")
@RestController
@RequestMapping("/teamHandover")
public class TeamHandoverController {

    private final static Logger logger = LoggerFactory.getLogger(TeamHandoverController.class);
    @Autowired
    private TeamHandoverService teamHandoverService;

    @ApiOperation("保存班组交接接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id，新增不传，修改传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "handoverCode", value = "交班人code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "handoverName", value = "交班人姓名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "receiverCode", value = "接班人code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "receiverName", value = "接班人姓名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dutyTeamName", value = "值班组", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dutyTime", value = "值班时间", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dutyTeamUserCode", value = "班组成员code，多个用，分割", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "dutyTeamUserName", value = "班组成员name，多个用，分割", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "deviceState", value = "设备状态，0-正常，1-异常", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "handoverExplain", value = "交接说明" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "备注" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "'状态,0-草稿，1.审核中，2.审批完成", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hiddenDangers", value = "隐患列表json格式" , dataType = "String", paramType = "query")
    }
    )
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存班组交接接口", businessModule = "班组交接", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<String> save(HttpServletRequest request, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                     @ApiIgnore TeamHandover bean, @RequestParam(required = false) String hiddenDangers,
                                     @RequestParam(required = false) final String keepFile,
                                     @RequestParam(required = false) final String delFile,
                                     @RequestParam(required = false) final MultipartFile[] file) {
        if (null == user) {
            MessageBean<String> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        TeamHandoverRelation relation = new TeamHandoverRelation();
        if (null != hiddenDangers) {
            List<DeviceHiddenDanger> deviceHiddenDangers = JSONObject.parseArray(hiddenDangers, DeviceHiddenDanger.class);
            relation.setHiddenDangerList(deviceHiddenDangers);
            if (deviceHiddenDangers != null && !deviceHiddenDangers.isEmpty()) {
                MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (int i = 0; i < deviceHiddenDangers.size(); i++) {
                            DeviceHiddenDanger deviceHiddenDanger = deviceHiddenDangers.get(i);
                            deviceHiddenDanger.setFiles(standardMultipartHttpServletRequest.getFiles("files" + i));
                        }
                    }
                }
            }
        }
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        return teamHandoverService.save(bean, relation, user, file, keepFile, delFile);
    }

    @ApiOperation("删除班组交接接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班组交接id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除班组交接", businessModule = "班组交接", businessManipulation = BusinessManipulation.DELETE)

    public MessageBean<Integer> delete(@RequestParam final String id, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return teamHandoverService.delete(id, user);
    }


    @ApiOperation("查询班组交接详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班组交接id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.GET)
    public MessageBean<TeamHandover> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            MessageBean<TeamHandover> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return teamHandoverService.queryOne(id);
    }


    @ApiOperation("查询班组交接详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "班组交接id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/getHiddenDangers.htm", method = RequestMethod.GET)
    public MessageBean<DataBean<HiddenDangerDiscovery>> getHiddenDangers(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize) {
        if (null == user) {
            MessageBean messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return teamHandoverService.getHiddenDangers(id,page,pageSize);
    }

    @ApiOperation("班组交接列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dutyTeamName", value = "值班组" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.GET)
    public MessageBean<DataBean<TeamHandover>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String corpCode,
                                                    @RequestParam(required = false) final String dutyTeamName,
                                                    @RequestParam(required = false) String keyword,
                                                    @RequestParam Integer page,
                                                    @RequestParam Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<TeamHandover>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<TeamHandover>> msg = teamHandoverService.list(corpCode, dutyTeamName, start, pageSize,keyword);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            MessageBean<?> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return teamHandoverService.getProcessData(ids);
    }


    @ApiOperation("班组交接列表导出接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dutyTeamName", value = "值班组" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/export.htm", method = RequestMethod.GET)
    public HttpEntity<?> export(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCode, String dutyTeamName) {
        if (null == user) {
            return null;
        }
        List<TeamHandover> list = teamHandoverService.export(user, corpCode, dutyTeamName);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/teamHandoverList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/teamHandoverList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("班组交接列表", targetFile, "teamHandoverList.btl", map);
    }
}
